﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System;
using System.Data;
using System.Linq;
using System.Data.SqlClient;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Topro.Web.Controllers
{
    using Dapper;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Tables;
    using Topro.Util;
    using Topro.Web.Request;

    /// <summary>
    /// 登录
    /// </summary>
    public class AccountController : Controller
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public AccountController(IDb db)
        {
            _db = db;
        }
        #endregion

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request">参数</param>
        [HttpPost]
        public async Task<JsonResult> Login(LoginRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //查询
                var userQuerySql = "select * from user WHERE Account=@Account";
                //新增
                var user = _db.DbConnection.Query<User>(userQuerySql, new { Account = request.Account }).FirstOrDefault();
                //加密
                var pass = EncryptionUtil.EncryptWithMd5(request.Password);
                //密码比较
                if (user.PassWord != EncryptionUtil.EncryptWithMd5(request.Password))
                {
                    throw new Exception("密码错误！");
                }

                if (user != null)
                {
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Sid,user.Id.ToString()),
                        new Claim(ClaimTypes.Name,user.Account)
                    };

                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

                    response.Success = true;
                }
                else
                {
                    response.Success = false;
                }
            }
            catch(Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }

            return Json(response);
        }

        /// <summary>
        /// 注销
        /// </summary>
        public IActionResult Logout()
        {
            Task.Run(async () =>
            {
                await HttpContext.SignOutAsync();
            }).Wait();

            return View("Index");
        }
    }
}
